package com.gin.kotlin.no_gay_alliance.model

import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.view.LayoutInflater
import android.webkit.JavascriptInterface
import android.webkit.WebView
import androidx.annotation.DrawableRes
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.base.AlertDialogUtils
import com.gin.kotlin.no_gay_alliance.base.IntRangeTextWatcher
import com.gin.kotlin.no_gay_alliance.base.MyHandler
import com.gin.kotlin.no_gay_alliance.callback.SCallback
import com.gin.kotlin.no_gay_alliance.databinding.DialogDiceBinding
import com.gin.kotlin.no_gay_alliance.enums.HandlerMessageWhat.POST_ADD_TEXT_TO_CONTENT
import com.gin.kotlin.no_gay_alliance.provider.ngajs.ColorProvider

/**
 * 发帖界面的代码快捷输入按钮
 * @property cn 中文名
 * @property icon 图标Res
 * @property longClick 是否提供了长按功能
 * @constructor
 */
enum class PostBbsCodeModel(
    val cn: String,
    @DrawableRes val icon: Int,
    val longClick:Boolean=false,
) {
    COLOR("颜色", R.drawable.ic_color_lens_24,true),
    SIZE("大小", R.drawable.ic_size_24),
    QUOTE("引用", R.drawable.ic_quote_24),
    COLLAPSE("折叠", R.drawable.ic_collapse),
    URL("链接", R.drawable.ic_add_link_24),
    DEL("删除线", R.drawable.ic_delete_line_24),
    BOLD("粗体", R.drawable.ic_bold_24),
    UNDERLINE("下划线", R.drawable.ic_underlined_24),
    ITALIC("斜体", R.drawable.ic_italic_24),
    HEADER("段落标题", R.drawable.ic_header),
    LIST("列表", R.drawable.ic_list),
    DICE("骰子", R.drawable.ic_dice,true),

    ;

    /**
     * 单击事件
     * @param context Context
     * @param handler MyHandler?
     */
    fun onClick(context: Context, handler: MyHandler? = null) {
        val model: PostAddTextModel = when (this) {
            COLOR -> PostAddTextModel("[color=red]", "[/color]")
            SIZE -> PostAddTextModel("[size=100%]", "[/size]")
            QUOTE -> PostAddTextModel("[quote]", "[/quote]")
            COLLAPSE -> PostAddTextModel("[collapse=折叠标题]", "[/collapse]")
            URL -> PostAddTextModel("[url=链接地址]", "[/url]")
            DEL -> PostAddTextModel("[del]", "[/del]")
            BOLD -> PostAddTextModel("[b]", "[/b]")
            UNDERLINE -> PostAddTextModel("[u]", "[/u]")
            ITALIC -> PostAddTextModel("[i]", "[/i]")
            HEADER -> PostAddTextModel("[h]", "[/h]")
            LIST -> PostAddTextModel("[list]\n[*]\n[*]\n[*]\n[/list]")
            DICE -> PostAddTextModel("[dice]1d100[/dice]")
        }
        handler?.sendMessage(POST_ADD_TEXT_TO_CONTENT, model)
    }

    fun onLongClick(context: Context, handler: MyHandler? = null): Boolean {
        when (this) {
            COLOR -> showColorSelector(context, handler)
            DICE -> showDiceOption(context, handler)
            else -> {}
        }
        return true
    }

    /**
     * 显示骰子选项弹窗
     * @param context Context
     * @param handler MyHandler?
     */
    private fun showDiceOption(context: Context, handler: MyHandler?) {
        val b = DialogDiceBinding.inflate(LayoutInflater.from(context))
        b.etLabelDiceCount.addTextChangedListener(IntRangeTextWatcher(b.etLabelDiceCount, 1))
        b.etLabelRandomRange.addTextChangedListener(IntRangeTextWatcher(b.etLabelRandomRange, 1))
        AlertDialogUtils.builder(context, title = "添加骰子", contentView = b.root, listener = { _, which ->
            val range = b.etLabelRandomRange.text.toString().toInt()
            val count = b.etLabelDiceCount.text.toString().toInt()
            if (which == DialogInterface.BUTTON_POSITIVE)
                handler?.sendMessage(POST_ADD_TEXT_TO_CONTENT, PostAddTextModel("[dice]${count}d${range}", "[/dice]"))
        }).show()
    }


    /**
     * 显示颜色选择弹窗
     * @param context Context
     * @param handler MyHandler?
     */
    private fun showColorSelector(context: Context, handler: MyHandler? = null) {
        val selector = context.assets.open("color_selector.html").bufferedReader().readText()
        val colorSpan = context.assets.open("color_span.html").bufferedReader().readText()
        ColorProvider.getInstance().enqueue(callback = object : SCallback<List<String>> {
            @SuppressLint("SetJavaScriptEnabled")
            override fun onSuccess(data: List<String>) {
                // 色块
                val spans = data.joinToString("") { colorSpan.replace("[颜色占位]", it) }
                // 完整HTML
                val html = selector.replace("[正文占位]", spans)
                val webView = WebView(context).also { it.settings.javaScriptEnabled = true }
                // 加载html代码
                webView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null)
                val dialog = AlertDialogUtils.builder(context, "选择颜色", contentView = webView).show()
                // 点击响应
                webView.addJavascriptInterface(object : Any() {
                    @JavascriptInterface
                    fun chooseColor(color: String) {
                        handler?.sendMessage(POST_ADD_TEXT_TO_CONTENT, PostAddTextModel("[color=${color}]", "[/color]"))
                        dialog.hide()
                    }
                }, "android")
            }

            override fun onFailure(call: okhttp3.Call, e: java.io.IOException) {
                e.printStackTrace()
            }
        })
    }
}